const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      pickerOptions: pickerOptions,
      dialogVisible: false,
      rules: {
        Category_Name: [{
          required: true,
          message: '请输入类别名称',
          trigger: 'blur',
        }]
      },
      fileList: [],
      fileList1: [],
      dialogImageUrl: '',
      dialogVisible: false,
      form: {
        Category_SerialNumber: "",
        Category_Name: '',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Picture_URL:''
      }, 
      pic:'', 
      loading: false
    }
  },
  mounted() {
    this.uploadFront()
  },
  methods: {
    submitForm(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.loading = true
          $.ajax({
            url: DomainName + '/GoodsFileAdd',
            type: 'POST',
            data: {
              Data: JSON.stringify({
                category: [_this.form]
              }),
              token: $.cookie("token")
            },
            success: function (res) {
              console.log('提交结果', res)
              _this.$message.success("提交成功")
              window.location.href = './Category.html'
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onExcel() {
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    uploadDetails(file) {
      this.fileList.push({
        name: file.name,
        url: file.type
      })
      let _this = this;
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        let lArray_ColumnsKeys = Object.keys(str[0]);
        let lJSONObject_Columns = { field: '', title: '', align: 'center', halign: 'center', width: 100 };
        let lJSONArray_Columns = [[]];

        $.each(lArray_ColumnsKeys, function (index, value) {
          let lJSONObject_Columns_Record = JSON.parse(JSON.stringify(lJSONObject_Columns));
          lJSONObject_Columns_Record.field = value;
          lJSONObject_Columns_Record.title = value;
          lJSONArray_Columns[0].push(lJSONObject_Columns_Record)
        });
        console.log(lJSONArray_Columns);
        console.log(str);
        //将整体数据分解成每一条，一条上传一次
        str.forEach((item, index) => {
          _this.fileList1.push({
            Category_SerialNumber: "",
            Category_Name: item['类别名称'],
          })
        })
      }
    },
    submitForm1() {
      console.log(this.fileList1);
      let _this = this
      $.ajax({
        url: DomainName + '/GoodsFileAdd',
        type: 'POST',
        data: {
          Data: JSON.stringify({
            category: _this.fileList1
          })
        },
        success: function (res) {
          if (res.Status === 'success') {
            _this.$message.success("操作成功")
            window.history.back()
          } else {
            _this.$message.error("操作失败，请稍后再试")
          }
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
      //商品封面图片
      uploadFront(file) {

        let _this = this
        let num = 1
        new Compressor(file, {
          quality: num,
          success(file) {
            console.log(file.size)
            const formData = new FormData();
            formData.append('file', file, file.name);
            let oFileReader = new FileReader();
            oFileReader.readAsDataURL(file);
            oFileReader.onload = function (e) {
              $.ajax({
                type: 'POST',
                url: DomainName + '/FileList',
                data: {
                  Data: e.target.result,
                  DataLength: file.size,
                  FileName: file.name
                },
                complete: function (XMLHttpRequest) {
                  _this.loading = false
                  if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                    window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                success: function (Result) {
                  _this.pic = e.target.result
                  if (Result.Status == "success") {
                    _this.form.Picture_URL = Result.Picture_Url
                    _this.$message.success('上传成功')
                    console.log(Result.Picture_Url);
                  } else {
                    _this.$message.error('上传失败')
                  }
                },
                error: function () {
                  _this.$message.error("操作失败，请稍后再试")
                },
                dataType: "json"
              });
            }
          },
          error(err) {
            console.log(err.message);
          },
        });
      },
  }
})